package com.coffee.mongodb;

import com.mongodb.MongoClientSettings;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.autoconfigure.mongo.MongoPropertiesClientSettingsBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.concurrent.TimeUnit;

/**
 * @author: songkui
 * @since: 2022/5/6 10:23
 */
@Configuration(proxyBeanMethods = false)
@ConditionalOnMissingBean(MongoClientSettings.class)
public class MochaMongoClientSettingsConfiguration {


    @Bean
    public MongoClientSettings mongoClientSettings(MochaMongoPoolProperties mochaMongoPoolProperties) {
        return MongoClientSettings.builder()
                .applicationName(mochaMongoPoolProperties.getAppName())
                .applyToSocketSettings((settings) -> {
                    settings.connectTimeout(mochaMongoPoolProperties.getConnectionTimeoutMs(), TimeUnit.MILLISECONDS);
                    settings.readTimeout(mochaMongoPoolProperties.getReadTimeoutMs(), TimeUnit.MILLISECONDS);
                })
                .applyToConnectionPoolSettings(settings -> {
                    settings.maxSize(mochaMongoPoolProperties.getMaxSize());
                    settings.minSize(mochaMongoPoolProperties.getMinSize());
                })
                .retryWrites(false) // TODO 重试机制，如果网路问题，操作会重试；
                .build();
    }

    @Bean
    public MongoPropertiesClientSettingsBuilderCustomizer mongoPropertiesCustomizer(MongoProperties properties,
                                                                             Environment environment) {
        return new MongoPropertiesClientSettingsBuilderCustomizer(properties, environment);
    }

}
